package cn.edu.fzu.delivery.net;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class LocalHost {

    private static final Logger       log         = LoggerFactory.getLogger(LocalHost.class);

    private static final Inet4Address ipv4        = get();
    private static final String       hostAddress = ipv4 == null ? "127.0.0.1" : ipv4.getHostAddress();
    private static final byte[]       address     = ipv4 == null ? new byte[4] : ipv4.getAddress();

    private LocalHost() {
    }


    public static final Inet4Address getIpv4() {
        return ipv4;
    }


    public static final String getHostAddress() {
        return hostAddress;
    }


    public static final byte[] getAddress() {
        return address;
    }


    private static final Inet4Address get() {

        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            InetAddress inetAddress;
            while (networkInterfaces.hasMoreElements()) {
                networkInterface = networkInterfaces.nextElement();
                if (networkInterface.isLoopback()) {
                    continue;
                }

                for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                    if (interfaceAddress == null || interfaceAddress.getNetworkPrefixLength() == 32) {
                        continue;
                    }

                    inetAddress = interfaceAddress.getAddress();
                    if (inetAddress instanceof Inet4Address) {
                        return (Inet4Address) inetAddress;
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

}
